package com.fatesgo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.fatesgo.pojo.RegisterUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.fatesgo.mapper.UserMapper;
import com.fatesgo.pojo.User;
import com.fatesgo.util.RedisUtil;
import com.fatesgo.util.Response;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    RedisUtil redisUtil;
    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 根据token获取用户信息
     */
    @GetMapping("/getUserInfo")
    public Response getUserInfoByToken() {
        String token = request.getHeader("token");
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> user = (Map<String, Object>) redisUtil.get("user_info" + token);
        if(user==null){
            return  Response.error("登录过期!");
        }
        JSONObject userInfo = new JSONObject(user);
        map.put("user", userInfo);
        return Response.success("成功", map);
    }

    @GetMapping("/getUserInfo/{id}")
    public Response getUserInfoById(@PathVariable("id") int id) {
        User user = userMapper.getUserInfoById(id);
        return Response.success("成功", user);
    }
    @PostMapping("/createUser")
    public Response createUser(@RequestBody User user) {
        int row = userMapper.createUser(user);
        return Response.success("成功", row);
    }

    @PutMapping("/updateUserInfo")
    public Response updateUserInfo(@RequestBody User user) {
        int row = userMapper.updateUserInfo(user);
        return Response.success("成功", row);
    }

    @PostMapping("/register")
    public Response register(@RequestBody RegisterUser user) {
        int row = userMapper.register(user);
        return Response.success("成功", row);
    }

    @DeleteMapping("/{id}")
    public Response deleteUser(@PathVariable("id") int id) {
        int row = userMapper.deleteUser(id);
        return Response.success("删除成功", row);
    }

    @GetMapping("/list")
    public Response list(User user, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        // 分页
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectAll(user);
        return Response.page(users, new PageInfo<User>(users).getTotal());
    }

}


